// 读取 cookie 的函数
function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let i = 0; i < cookies.length; i++) {
        const parts = cookies[i].split('=');
        if (parts[0] === name) {
            return decodeURIComponent(parts[1]);
        }
    }
    return null;
}

let currentAdminId = getCookie('user_id');
console.log('当前管理员 ID:', currentAdminId);
if (!currentAdminId || isNaN(currentAdminId)) {
    currentAdminId = null;
} else {
    currentAdminId = parseInt(currentAdminId, 10);
}

let currentAdminName = getCookie('admin_name');
if (!currentAdminName) {
    currentAdminId = null;
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取当前管理员信息
    fetchAdminInfo();

    // 菜单切换
    const menuItems = document.querySelectorAll('.menu-item');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除所有active类
            menuItems.forEach(i => i.classList.remove('active'));
            // 添加当前active类
            this.classList.add('active');

            // 隐藏所有页面
            document.querySelectorAll('.page-content').forEach(page => {
                page.style.display = 'none';
            });

            // 显示当前页面
            const pageId = this.getAttribute('data-page') + '-page';
            document.getElementById(pageId).style.display = 'block';

            // 根据页面加载数据
            switch(this.getAttribute('data-page')) {
                case 'user-management':
                    loadUsers();
                    break;
                case 'course-management':
                    loadCourses();
                    break;
                case 'teacher-management':
                    loadTeachers();
                    break;
                case 'student-management':
                    loadStudents();
                    break;
            }
        });
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            // 实际应用中这里应该清除登录状态并跳转到登录页面
             window.location.href = 'index.html';
            alert('已退出登录');
        }
    });

    // 用户管理事件
    document.getElementById('addUserBtn').addEventListener('click', openUserModal);
    document.getElementById('user-search-btn').addEventListener('click', searchUsers);
    document.getElementById('user-search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') searchUsers();
    });

    // 课程管理事件
    document.getElementById('addCourseBtn').addEventListener('click', openCourseModal);
    document.getElementById('course-search-btn').addEventListener('click', searchCourses);
    document.getElementById('course-search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') searchCourses();
    });

    // 用户模态框事件
    document.getElementById('closeUserModal').addEventListener('click', closeUserModal);
    document.getElementById('cancelUser').addEventListener('click', closeUserModal);
    document.getElementById('saveUser').addEventListener('click', saveUser);

    // 课程模态框事件
    document.getElementById('closeCourseModal').addEventListener('click', closeCourseModal);
    document.getElementById('cancelCourse').addEventListener('click', closeCourseModal);
    document.getElementById('saveCourse').addEventListener('click', saveCourse);

    // 角色切换标签
    document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            document.querySelectorAll('.role-form').forEach(form => {
                form.classList.remove('active');
            });

            document.getElementById(this.getAttribute('data-role') + '-form').classList.add('active');
        });
    });

    // 角色选择变化时显示对应表单
    document.getElementById('user-role').addEventListener('change', function() {
        document.querySelectorAll('.role-form').forEach(form => {
            form.classList.remove('active');
        });

        if (this.value === 'student') {
            document.getElementById('student-form').classList.add('active');
        } else if (this.value === 'teacher') {
            document.getElementById('teacher-form').classList.add('active');
        } else {
            document.getElementById('common-form').classList.add('active');
        }
    });

    // 删除模态框事件
    document.getElementById('closeDeleteModal').addEventListener('click', closeDeleteModal);
    document.getElementById('cancelDelete').addEventListener('click', closeDeleteModal);
    document.getElementById('confirmDelete').addEventListener('click', confirmDelete);

    // 点击页面其他地方关闭模态框
    window.addEventListener('click', function(event) {
        if (event.target === document.getElementById('userModal')) {
            closeUserModal();
        }
        if (event.target === document.getElementById('courseModal')) {
            closeCourseModal();
        }
        if (event.target === document.getElementById('deleteModal')) {
            closeDeleteModal();
        }
    });

    // 默认加载用户数据
    loadUsers();
});

// 获取管理员信息
function fetchAdminInfo() {
    // 假设从cookie获取管理员ID
     document.getElementById('adminName').textContent = currentAdminName;
}

// 加载用户数据
function loadUsers() {
    // 调用AdminController中的/admin/users接口
    fetch(`/admin/users`)
        .then(response => response.json())
        .then(data => {
            renderUsers(data);
        })
        .catch(error => {
            console.error('获取用户列表出错:', error);
            document.getElementById('users-error').textContent = '获取用户列表失败';
            document.getElementById('users-error').style.display = 'block';
        });
}

// 搜索用户
function searchUsers() {
    const name = document.getElementById('user-search').value.trim();
    // 调用AdminController中的/admin/users/query接口
    fetch(`/admin/users/query?name=${name}`)
        .then(response => response.json())
        .then(data => {
            renderUsers(data);
        })
        .catch(error => {
            console.error('搜索用户出错:', error);
            document.getElementById('users-error').textContent = '搜索用户失败';
            document.getElementById('users-error').style.display = 'block';
        });
}

// 渲染用户列表
function renderUsers(users) {
    const tableBody = document.getElementById('users-table');
    tableBody.innerHTML = '';

    if (!users || users.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center;">暂无用户数据</td></tr>';
        return;
    }

    users.forEach(user => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.realName || '未设置'}</td>
            <td>${getRoleName(user.role)}</td>
            <td>${formatDate(user.createdAt)}</td>
            <td>
                <button class="action-btn edit-btn" data-id="${user.id}" data-type="user">编辑</button>
                <button class="action-btn delete-btn" data-id="${user.id}" data-name="${user.username || '未设置'}" data-type="user">删除</button>
            </td>
        `;
        tableBody.appendChild(row);
    });

    // 绑定编辑按钮事件
    document.querySelectorAll('.edit-btn[data-type="user"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const userId = this.getAttribute('data-id');
            editUser(userId);
        });
    });

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn[data-type="user"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const userId = this.getAttribute('data-id');
            const userName = this.getAttribute('data-name');
            openDeleteModal(userId, userName, 'user');
        });
    });
}

// 加载课程数据
function loadCourses() {
    // 调用CourseController中的/course/query接口
    fetch(`/course/query`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderCourses(data.data);
            } else {
                throw new Error(data.msg || '获取课程列表失败');
            }
        })
        .catch(error => {
            console.error('获取课程列表出错:', error);
            document.getElementById('courses-error').textContent = error.message;
            document.getElementById('courses-error').style.display = 'block';
        });
}

// 搜索课程
function searchCourses() {
    const name = document.getElementById('course-search').value.trim();
    // 调用CourseController中的/course/query接口
    fetch(`/course/query?courseName=${name}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderCourses(data.data);
            } else {
                throw new Error(data.msg || '搜索课程失败');
            }
        })
        .catch(error => {
            console.error('搜索课程出错:', error);
            document.getElementById('courses-error').textContent = error.message;
            document.getElementById('courses-error').style.display = 'block';
        });
}

// 渲染课程列表
function renderCourses(courses) {
    const tableBody = document.getElementById('courses-table');
    tableBody.innerHTML = '';

    if (!courses || courses.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无课程数据</td></tr>';
        return;
    }

    courses.forEach(course => {
        const row = document.createElement('tr');
        row.innerHTML = `
                    <td>${course.id}</td>
                    <td>${course.cno || '未设置'}</td>
                    <td>${course.cname}</td>
                    <td>${course.chours}课时</td>
                    <td>${course.teacherName || '未分配'}</td>
                    <td>${course.status === 'yes' ? '启用' : '停用'}</td>
                    <td>
                        <button class="action-btn edit-btn" data-id="${course.id}" data-type="course">编辑</button>
                        <button class="action-btn delete-btn" data-id="${course.id}" data-name="${course.cname}" data-type="course">删除</button>
                    </td>
                `;
        tableBody.appendChild(row);
    });

    // 绑定编辑按钮事件
    document.querySelectorAll('.edit-btn[data-type="course"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.getAttribute('data-id');
            editCourse(courseId);
        });
    });

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn[data-type="course"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.getAttribute('data-id');
            const courseName = this.getAttribute('data-name');
            openDeleteModal(courseId, courseName, 'course');
        });
    });
}

async function loadTeachers() {
    try {
        const url = '/admin/users';
        const response = await fetch(url);
        const data = await response.json();
        console.log('从 /admin/users 获取的数据:', data);

        const teacherIds = data.filter(user => user.role === 'teacher').map(user => user.id);
        console.log('提取的教师 ID:', teacherIds);

        const teacherDetails = await Promise.all(
            teacherIds.map(async id => {
                const teacherResponse = await fetch(`/teacher/query/${id}`);
                const teacherData = await teacherResponse.json();
                console.log(`教师 ID ${id} 的响应:`, teacherData);
                return teacherData;
            })
        );

        // 提取真正的教师数据
        const validTeachers = teacherDetails
            .filter(response => {
                // 根据实际返回的数据结构调整判断条件
                return response.code === 200 && response.data;
            })
            .map(response => response.data);
        console.log('提取后的教师数据:', validTeachers);

        renderTeachers(validTeachers);
    } catch (error) {
        console.error('获取教师列表出错:', error);
        document.getElementById('teachers-error').textContent = '获取教师列表失败';
        document.getElementById('teachers-error').style.display = 'block';
    }
}



// 渲染教师列表
function renderTeachers(teachers) {
    const tableBody = document.getElementById('teachers-table');
    tableBody.innerHTML = '';

    if (!teachers || teachers.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无教师数据</td></tr>';
        return;
    }

    teachers.forEach(teacher => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${teacher.userId || '未知1'}</td>
            <td>${teacher.tno || '未知'}</td>
            <td>${teacher.tname || '未设置'}</td>
            <td>${teacher.gender || '未知'}</td>
            <td>
                <button class="action-btn edit-btn" data-id="${teacher.user_id || ''}" data-type="teacher">编辑</button>
                <button class="action-btn delete-btn" data-id="${teacher.user_id || ''}" data-name="${teacher.tname || '未知'}" data-type="teacher">删除</button>
            </td>
        `;
        tableBody.appendChild(row);
    });

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn[data-type="teacher"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const teacherId = this.getAttribute('data-id');
            const teacherName = this.getAttribute('data-name');
            openDeleteModal(teacherId, teacherName, 'teacher');
        });
    });
}


// 加载学生数据
// 加载学生数据
async function loadStudents() {
    try {
        const url = '/admin/users';
        const response = await fetch(url);
        const data = await response.json();
        console.log('从 /admin/users 获取的数据:', data);

        // 筛选出学生用户的 ID
        const studentIds = data.filter(user => user.role === 'student').map(user => user.id);
        console.log('提取的学生 ID:', studentIds);

        // 并发获取每个学生的详细信息
        const studentDetails = await Promise.all(
            studentIds.map(async id => {
                const studentResponse = await fetch(`/student/${id}`);
                const studentData = await studentResponse.json();
                console.log(`学生 ID ${id} 的响应:`, studentData);
                return studentData;
            })
        );

        // 提取真正的学生数据
        const validStudents = studentDetails
            .filter(response => {
                // 假设学生接口返回数据结构和教师接口类似，根据实际情况调整
                return response.code === 200 && response.data;
            })
            .map(response => response.data);
        console.log('提取后的学生数据:', validStudents);

        renderStudents(validStudents);
    } catch (error) {
        console.error('获取学生列表出错:', error);
        document.getElementById('students-error').textContent = '获取学生列表失败';
        document.getElementById('students-error').style.display = 'block';
    }
}


// 渲染学生列表
function renderStudents(students) {
    const tableBody = document.getElementById('students-table');
    tableBody.innerHTML = '';

    if (!students || students.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无学生数据</td></tr>';
        return;
    }

    students.forEach(student => {
        const row = document.createElement('tr');
        row.innerHTML = `
                    <td>${student.userId||'未知'}</td>
                    <td>${student.sno}</td>
                    <td>${student.sname}</td>
                    <td>${student.gender}</td>
                    <td>
                        <button class="action-btn edit-btn" data-id="${student.user_id}" data-type="student">编辑</button>
                        <button class="action-btn delete-btn" data-id="${student.user_id}" data-name="${student.sname}" data-type="student">删除</button>
                    </td>
                `;
        tableBody.appendChild(row);
    });

    // 绑定编辑按钮事件

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn[data-type="student"]').forEach(btn => {
        btn.addEventListener('click', function() {
            const studentId = this.getAttribute('data-id');
            const studentName = this.getAttribute('data-name');
            openDeleteModal(studentId, studentName, 'student');
        });
    });
}

// 打开用户模态框
function openUserModal() {
    resetUserForm();
    document.getElementById('userModalTitle').textContent = '添加用户';
    document.getElementById('userModal').style.display = 'flex';
}

// 编辑用户
function editUser(userId) {
    let user;
    // 调用AdminController中的/admin/users接口获取用户详情
    fetch(`/admin/query/user/${userId}`, {
        method: "GET"
    }).then(
        response => response.json()
    ).then(data => {
        user = JSON.parse(JSON.stringify(data.data));
        document.getElementById('user-id').value = user.id;
        document.getElementById('user-username').value = user.username;
        document.getElementById('user-password').value = '';
        document.getElementById('user-realname').value = user.realName;
        document.getElementById('user-role').value = user.role;
        document.getElementById('user-role').dispatchEvent(new Event('change'));
        document.getElementById('userModalTitle').textContent = '编辑用户';
        document.getElementById('userModal').style.display = 'flex';
    });
}

// 打开课程模态框
function openCourseModal() {
    resetCourseForm();
    document.getElementById('courseModalTitle').textContent = '添加课程';
    document.getElementById('courseModal').style.display = 'flex';
}

// 编辑课程
function editCourse(courseId) {
    // 调用CourseController中的/course/query接口获取课程详情
    fetch(`/course/query/${courseId}`, {
        method: "GET"
    }).then(response => response.json()).then(data => {
        course = JSON.parse(JSON.stringify(data.data));
        document.getElementById('course-id').value = course.id;
        document.getElementById('course-cno').value = course.cno;
        document.getElementById('course-cname').value = course.cname;
        document.getElementById('course-chours').value = course.chours;
        document.getElementById('course-status').value = course.status;
        document.getElementById('course-teacher').value = course.teacherName || '';
        document.getElementById('course-classcode').value = course.classcode || '';

        document.getElementById('courseModalTitle').textContent = '编辑课程';
        document.getElementById('courseModal').style.display = 'flex';
    })
}

// 打开删除确认模态框
function openDeleteModal(id, name, type) {
    document.getElementById('delete-item-name').textContent = name;
    document.getElementById('confirmDelete').setAttribute('data-id', id);
    document.getElementById('confirmDelete').setAttribute('data-type', type);
    document.getElementById('deleteModal').style.display = 'flex';
}

// 关闭用户模态框
function closeUserModal() {
    document.getElementById('userModal').style.display = 'none';
}

// 关闭课程模态框
function closeCourseModal() {
    document.getElementById('courseModal').style.display = 'none';
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
}

// 重置用户表单
function resetUserForm() {
    document.getElementById('user-id').value = '';
    document.getElementById('user-username').value = '';
    document.getElementById('user-password').value = '';
    document.getElementById('user-realname').value = '';
    document.getElementById('user-role').value = 'student';
    document.getElementById('student-sno').value = '';
    document.getElementById('student-gender').value = '男';
    document.getElementById('teacher-tno').value = '';
    document.getElementById('teacher-gender').value = '男';

    // 重置标签
    document.querySelectorAll('.tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector('.tab[data-role="common"]').classList.add('active');

    document.querySelectorAll('.role-form').forEach(form => {
        form.classList.remove('active');
    });
    document.getElementById('common-form').classList.add('active');
}

// 重置课程表单
function resetCourseForm() {
    document.getElementById('course-id').value = '';
    document.getElementById('course-cno').value = '';
    document.getElementById('course-cname').value = '';
    document.getElementById('course-chours').value = '';
    document.getElementById('course-status').value = 'yes';
    document.getElementById('course-teacher').value = '';
    document.getElementById('course-classcode').value = '';
}

// 保存用户
function saveUser() {
    const userId = document.getElementById('user-id').value;
    const username = document.getElementById('user-username').value;
    const password = document.getElementById('user-password').value;
    const realName = document.getElementById('user-realname').value;
    const role = document.getElementById('user-role').value;

    // 验证表单
    if (!username || !password || !realName) {
        alert('请填写必填字段');
        return;
    }

    const user = {
        id: userId || null,
        username: username,
        password: password,
        realName: realName,
        role: role
    };

    let student = null;
    let teacher = null;

    if (role === 'student') {
        const sno = document.getElementById('student-sno').value;
        const gender = document.getElementById('student-gender').value;

        if (!sno) {
            alert('请填写学号');
            return;
        }

        student = {
            userId: userId || null,
            sno: sno,
            sname: realName,
            gender: gender
        };
    } else if (role === 'teacher') {
        const tno = document.getElementById('teacher-tno').value;
        const gender = document.getElementById('teacher-gender').value;

        if (!tno) {
            alert('请填写教师号');
            return;
        }

        teacher = {
            userId: userId || null,
            tno: tno,
            tname: realName,
            gender: gender
        };
    }

    let register = {
        user: user,
        student: student,
        teacher: teacher
    }

    // 调用AdminController中的/admin/insert或/admin/update接口
    if (userId) {
        // 更新用户
        fetch(`/admin/update`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
        })
            .then(response => response.text())
            .then(message => {
                alert('用户更新成功: ' + message);
                closeUserModal();
                loadUsers();
            })
            .catch(error => {
                console.error('更新用户出错:', error);
                alert('更新用户失败');
            });
    } else {
        // 添加用户
        const requestData = {
            user: user,
            student: student,
            teacher: teacher
        };

        fetch(`/admin/insert`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
            .then(response => response.text())
            .then(message => {
                alert('用户添加成功: ' + message);
                closeUserModal();
                loadUsers();
            })
            .catch(error => {
                console.error('添加用户出错:', error);
                alert('添加用户失败');
            });
    }
}

// 保存课程
function saveCourse() {
    const courseId = document.getElementById('course-id').value;
    const cno = document.getElementById('course-cno').value;
    const cname = document.getElementById('course-cname').value;
    const chours = document.getElementById('course-chours').value;
    const status = document.getElementById('course-status').value;
    const teacherName = document.getElementById('course-teacher').value;
    const classcode = document.getElementById('course-classcode').value;

    // 验证表单
    if (!cno || !cname || !chours) {
        alert('请填写必填字段');
        return;
    }

    const course = {
        id: courseId || null,
        cno: cno,
        cname: cname,
        chours: parseInt(chours),
        status: status,
        teacherName: teacherName,
        classcode: classcode ? parseInt(classcode) : null
    };

    console.log(course);

    // 调用CourseController中的/course/insert或/course/update接口
    const endpoint = course.id === null ? '/course/insert' : '/course/update';

    console.log(endpoint);

    fetch(`${endpoint}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(course)
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 || data === 1) {
                alert('课程保存成功');
                closeCourseModal();
                loadCourses();
            } else {
                alert('课程保存失败: ' + (data.msg || '未知错误'));
            }
        })
        .catch(error => {
            console.error('保存课程出错:', error);
            alert('保存课程失败');
        });
}

// 确认删除
function confirmDelete() {
    const name = document.getElementById('delete-item-name').textContent;
    const type = this.getAttribute('data-type');
    const id = this.getAttribute('data-id');

    // 根据类型调用不同的删除接口
    if (type === 'user') {
        // 调用AdminController中的/admin/users/deleteByName接口
        fetch(`/admin/users/deleteById?id=${id}`, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                if (data > 0) {
                    alert('用户删除成功');
                    closeDeleteModal();
                    loadUsers();
                } else {
                    alert('用户删除失败');
                }
            })
            .catch(error => {
                console.error('删除用户出错:', error);
                alert('删除用户失败');
            });
    } else if (type === 'course') {
        // 调用CourseController中的/course/delete/{courseId}接口
        fetch(`/course/delete/${id}`, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    alert('课程删除成功');
                    closeDeleteModal();
                    loadCourses();
                } else {
                    alert('课程删除失败: ' + (data.msg || '未知错误'));
                }
            })
            .catch(error => {
                console.error('删除课程出错:', error);
                alert('删除课程失败');
            });
    } else if (type === 'teacher' || type === 'student') {
        // 实际应用中应调用教师或学生删除接口
        alert(`删除${type === 'teacher' ? '教师' : '学生'}成功`);
        closeDeleteModal();
        if (type === 'teacher') {
            loadTeachers();
        } else {
            loadStudents();
        }
    }
}

// 辅助函数：获取角色名称
function getRoleName(role) {
    switch(role) {
        case 'admin': return '管理员';
        case 'teacher': return '教师';
        case 'student': return '学生';
        default: return role;
    }
}

// 辅助函数：格式化日期
function formatDate(dateString) {
    if (!dateString) return null;
    const date = new Date(dateString);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}